<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar title="编辑资料" left-arrow @click-left="$router.back()" />
    <!-- 头像区域 -->
    <div class="avatar-box">
      <van-image :src="userInfo.photo" round fit="cover"></van-image>
      <van-uploader :after-read="afterRead" />
    </div>
    <!-- 资料区域 -->
    <van-cell-group>
      <van-cell
        @click="clickNameCell"
        title="名称"
        :value="userInfo.name"
        is-link
      />
      <van-cell @click="genderShow = true" title="性别" :value="userInfo.gender ? '男' : '女'" is-link />
      <van-cell
        @click="clickBirthCell"
        title="生日"
        :value="userInfo.birthday"
        is-link
      />
    </van-cell-group>

    <!-- 图片裁剪区域 -->
    <div v-if="cropShow" class="crop-box">
      <vueCropper
        ref="cropper"
        :img="cropImg"
        autoCrop
        autoCropWidth="200"
        autoCropHeight="200"
      ></vueCropper>

      <van-button @click="doCrop" type="primary">裁剪</van-button>
      <van-button @click="cropShow = false" type="primary">取消</van-button>
    </div>

    <!-- 弹出框区域 -->
    <van-dialog
      @confirm="changeName"
      v-model="nameShow"
      title="修改昵称"
      show-cancel-button
    >
      <input
        ref="inp"
        v-model.trim="nameValue"
        class="name-input"
        type="text"
      />
    </van-dialog>

    <!-- 生日弹出层 -->
    <van-popup v-model="birthShow" position="bottom" :style="{ height: '30%' }">
      <van-datetime-picker
        @confirm="changeBirthday"
        @cancel="birthShow = false"
        v-model="currentDate"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
      />
    </van-popup>

    <!-- 修改性别的弹出层 -->
    <van-popup
      v-model="genderShow"
      position="bottom"
      :style="{ height: '20%' }"
    >
      <van-nav-bar title="修改性别" left-text="取消" @click-left="genderShow = false"/>
      <van-cell @click="changeGender(1)" title="男" is-link />
      <van-cell @click="changeGender(0)" title="女" is-link />
    </van-popup>
  </div>
</template>

<script>
import { VueCropper } from 'vue-cropper'
import { avatarAPI, profileAPI } from '@/api/user'
import dayjs from 'dayjs'
export default {
  name: 'UserEdit',
  components: {
    VueCropper
  },
  computed: {
    userInfo () {
      return this.$store.state.userInfo
    }
  },
  data () {
    return {
      minDate: new Date(1949, 9, 1),
      maxDate: new Date(),
      currentDate: new Date('2021-01-17'),
      birthShow: false,
      nameShow: false,
      nameValue: '',
      cropShow: false,
      cropImg: '',
      genderShow: false
    }
  },
  methods: {
    // 修改性别
    async changeGender (gender) {
      // 发请求
      await profileAPI({
        gender
      })

      // 隐藏弹出层
      this.genderShow = false
      // 让界面更新
      this.$store.commit('setUserInfo', {
        ...this.userInfo,
        gender
      })
    },
    // 选择完文件调用
    afterRead (file) {
      // 参数有两个属性：
      // file属性：可以得到你选择的文件对象
      // content属性： 得到选中文件的base64编码格式
      this.cropImg = file.content
      this.cropShow = true
    },

    // 裁剪的点击事件
    doCrop () {
      // 获取裁剪后的图片，得到的是一个图片对象
      this.$refs.cropper.getCropBlob(async data => {
        // 我现在相当于要给接口传一张图片
        // 如果要用ajax（axios）给接口发送文件，必须用FormData来传递
        const fm = new FormData()
        fm.append('photo', data)
        // 然后把FormData对象给axios发请求
        const res = await avatarAPI(fm)

        // 上传成功隐藏裁剪盒子
        this.cropShow = false
        // 还要把得到的上传后的图片保存到vuex里
        this.$store.commit('setUserInfo', {
          ...this.userInfo,
          photo: res.data.photo
        })
      })
    },
    // 点击名字cell触发的事件
    clickNameCell () {
      // 1. 显示出弹出框 -- dom渲染是异步的
      this.nameShow = true
      // 2. 把当前名字赋值给input
      this.nameValue = this.userInfo.name
      // 3. 让input获得焦点
      this.$nextTick(() => {
        this.$refs.inp.focus()
      })
    },

    // 修改名字
    async changeName () {
      // 1. 先非空判断
      if (this.nameValue === '') return this.$toast('请输入名字')
      // 2. 发请求给服务器做修改
      await profileAPI({
        name: this.nameValue
      })
      // 3. 隐藏弹出框
      this.nameShow = false

      // 4. 修改到vuex里
      this.$store.commit('setUserInfo', {
        ...this.userInfo,
        name: this.nameValue
      })
    },

    // 点击生日cell
    clickBirthCell () {
      // 1. 显示出弹出层
      this.birthShow = true
      // 2. 把当前生日给时间选择器
      this.currentDate = new Date(this.userInfo.birthday)
    },

    // 修改生日
    async changeBirthday () {
      // 拿到当前选择的日期，发请求给服务器
      // 先把日期对象转成字符串
      const birthday = dayjs(this.currentDate).format('YYYY-MM-DD')
      await profileAPI({
        birthday
      })
      // 修改到vuex里
      this.$store.commit('setUserInfo', {
        ...this.userInfo,
        birthday
      })
      // 隐藏弹出层
      this.birthShow = false
    }
  },
  async created () {
    this.$store.dispatch('reqUserInfo')
  }
}
</script>

<style lang="scss" scoped>
.avatar-box {
  $height: 140px;
  height: $height;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
  .van-image {
    width: 120px;
    height: 120px;
  }
  .van-uploader {
    position: absolute;
    left: 0;
    top: 0;
    ::v-deep .van-uploader__upload {
      width: 100vw;
      height: $height;
      opacity: 0;
    }
  }
}

.crop-box {
  width: 100vw;
  height: 100vh;
  position: fixed;
  left: 0;
  top: 0;

  .van-button {
    position: absolute;
    bottom: 0;

    &:nth-of-type(1) {
      left: 0;
    }
    &:nth-of-type(2) {
      right: 0;
    }
  }
}

.name-input {
  width: 100%;
  height: 40px;
  border-top: 1px solid #ddd;
  border-bottom: 1px solid #ddd;
  padding-left: 10px;
  border-left: none;
}
</style>
